package netty.test11HttpServer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.apache.http.client.methods.HttpHead;

import java.net.URI;

/**
 * HttpObject 是客户端和服务器端通讯的数据被封装成 httpObject
 * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter 的子类
 * ，pipleLine 和handler 是每一个客户端 都对应一个实列
 *
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
        System.out.println("没一个客户端一个 handler 实例 hashcode="+this.hashCode());
        //1,判断 httpObject 是不是http 请求
        if(httpObject instanceof HttpRequest){
            System.out.println("httpObject 的类型 ="+httpObject.getClass());
            System.out.println("客户端的地址为="+ctx.channel().remoteAddress());

            //2,过滤掉某些请求
            HttpRequest request=(HttpRequest)httpObject;
            URI uri = new URI(request.uri());//通过uri 过滤指定资源
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了 favicon.ico 不做响应");
                return;
            }

            //3，回复信息给浏览器（注意这里要回复 http 协议格式的信息）

            ByteBuf content= Unpooled.copiedBuffer("hello 我是服务器。。。", CharsetUtil.UTF_8);
            //构造一个http 协议的 response;(netty 有提供的默认的，http协议格式的对象)
            FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
            httpResponse.headers().set(HttpHeaderNames.CONNECTION,"Keep-alive");
            //3,将构建好的 response 返回
            ctx.writeAndFlush(httpResponse);
        }
    }
}
